package com.heima.netty.eventloop;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * Netty 客户端 入门案例
 * @author ZhengDp
 * @Date 2023/6/24 17:59
 */
@Slf4j
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        Channel channel = new Bootstrap()
                .group(new NioEventLoopGroup())
                // 选择客户端 Channel 实现
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    // 连接建立后，initChannel方法被调用
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 将 字符串 编码为 ByteBuffer --> 发送数据
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost",7777))
                .sync()
                .channel();
        System.out.println(channel);
        System.out.println();
    }
}
